<?php

/**
 *    自动交易
 *
 *    @author    Garbin
 *    @usage    none
 */
class CleanupTask extends BaseTask
{
    function run()
    {
        /* 自动确认收货 */
        $this->_auto_confirm();

        /* 自动好评 */
        $this->_auto_evaluate();

        /* 关闭过期店铺 */
        $this->_close_expired_store();

        /* 团购活动自动开始 */
        $this->_group_auto_start();

        /* 自动结束团购 */
        $this->_group_auto_end();

        /* 自动取消团购 */
        $this->_group_auto_cancel();
		
		/* 自动备份 */
		$this->_db_backup();
    }
function _db_backup(){
        if (!is_file(ROOT_PATH . "/data/db_backup.inc.php"))
            {
                $default_tasks = array(
                    "due_time" =>gmtime()+86400
                );
                file_put_contents(ROOT_PATH . "/data/db_backup.inc.php", "<?php\r\n\r\nreturn " . var_export($default_tasks, true) . ";\r\n\r\n", LOCK_EX);
            }else{
                $db_time = include(ROOT_PATH . "/data/db_backup.inc.php");
                if($db_time['due_time']>gmtime()){
                    return;
                }
            }
            
        
        import('db_back.lib');
        $db_back = new db_back();
        $db_back->backup();
        
        //删掉旧备份
        $dir = ROOT_PATH . "/data/sql_backup";
        $son_dir=array();
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
    if(preg_match('/\d{8}_auto/', $file)){
        $son_dir[]=$file;
    }
    
} 
closedir($dh);
while(is_array($son_dir) && count($son_dir)>10){
   arsort($son_dir);
   $dir_name=end($son_dir);
   array_pop($son_dir);
   is_dir($dir.'/'.$dir_name) && ecm_rmdir($dir.'/'.$dir_name);
}
}
}
    }
    /**
     *    自动确认指定时间后未确认收货的订单
     *
     *    @author    Garbin
     *    @param    none
     *    @return    void
     */
    function _auto_confirm()
    {
        //获取当前 已发货的 ORDER_SHIPPED   并且支付方式 payment_code !='bank' AND payment_code !='cod' AND payment_code !='post'    auto_finished_time 大于系统设置的数值
        $model_order = & m('order');
        
        $conditions = "payment_code !='bank' AND payment_code !='cod' AND payment_code !='post' AND status=" . ORDER_SHIPPED . " AND auto_finished_time<" . gmtime() ;
        $orders = $model_order->findAll(array(
            'conditions' => $conditions,
			'limit'=>10
        ));
        if (!empty($orders)) {
            foreach ($orders as $key => $order_info) {
                $this->auto_confirm($order_info);
            }
        }
    }

    function auto_confirm($order_info) {
        $order_id = $order_info['order_id'];
        $model_order = & m('order');
        $model_order->db->query('start transaction');
        $mysql_flag=$model_order->edit($order_id, array('status' => ORDER_FINISHED, 'finished_time' => gmtime()));
        if(!$mysql_flag){
                $model_order->db->query('rollback');
                return;
            }
        /* 记录订单操作日志 */
        $order_log = & m('orderlog');
        $remark = '确认收货超时,系统自动确认收货';
        $mysql_flag=$order_log->add(array(
            'order_id' => $order_id,
            'operator' => 'system',
            'order_status' => order_status($order_info['status']),
            'changed_status' => order_status(ORDER_FINISHED),
            'remark' => $remark,
            'log_time' => gmtime(),
            'operator_type' => 'buyer',
        ));
        if(!$mysql_flag){
                $model_order->db->query('rollback');
                return;
            }
        $account_log_mod=& m('account_log');
        $member_mod=& m('member');
        /* 更新定单状态 开始***************************************************** */
        $account_log_row = $account_log_mod->get("order_id='$order_id' and type=" . ACCOUNT_TYPE_BUY);
        $money = $account_log_row['money']; //定单价格
        $sell_user_id = $order_info['seller_id']; //卖家ID
        $buyer_user_id = $account_log_row['user_id']; //买家ID
        if ($account_log_row['order_id'] == $order_id) {

            $sell_money_row = $member_mod->getAll('SELECT * FROM '.$member_mod->table.' WHERE user_id='.$sell_user_id.' FOR UPDATE');
                    if(!is_array($sell_money_row) || empty($sell_money_row)){
                        $model_order->db->query('rollback');
                        return;
                    }
                    $sell_money_row=current($sell_money_row);
            $sell_money = $sell_money_row['money']; //卖家的资金
            $sell_money_dj = $sell_money_row['money_dj']; //卖家的冻结资金
            $new_money = $sell_money + $money;
            $new_money_dj = $sell_money_dj - $money;
            //更新数据
            $new_money_array = array(
                'money' => $new_money,
                'money_dj' => $new_money_dj,
            );
            $new_buyer_account_log = array(
                'money' => $money,
                'complete' => 1,
                'states' => 40,
            );
            $new_seller_account_log = array(
                'money' => $money,
                'complete' => 1,
                'states' => 40,
            );
            $mysql_flag=$member_mod->edit('user_id=' . $sell_user_id, $new_money_array);
            if(!$mysql_flag){
                $model_order->db->query('rollback');
                return;
            }
            $mysql_flag=$account_log_mod->edit("order_id={$order_id} AND user_id={$sell_user_id}", $new_seller_account_log);
            if(!$mysql_flag){
                $model_order->db->query('rollback');
                return;
            }
            $mysql_flag=$account_log_mod->edit("order_id={$order_id} AND user_id={$buyer_user_id}", $new_buyer_account_log);
            if(!$mysql_flag){
                $model_order->db->query('rollback');
                return;
            }
        }
        /* 更新定单状态 结束***************************************************** */


        /* 更新累计销售件数 */
        $model_goodsstatistics = & m('goodsstatistics');
        $model_ordergoods = & m('ordergoods');
        $order_goods = $model_ordergoods->find("order_id={$order_id}");
        foreach ($order_goods as $goods) {
            $model_goodsstatistics->edit($goods['goods_id'], "sales=sales+{$goods['quantity']}");
        }

            //为资金管理才可以扣除金额
        if ($order_info['payment_code'] != 'cod' && $order_info['payment_code'] != 'bank' && $order_info['payment_code'] != 'post') {
            /* 交易成功后,推荐者可以获得佣金  BEGIN */
            import('tuijian.lib');
            $tuijian = new tuijian();
            $mysql_flag=$tuijian->do_tuijian($order_info);
            if(!$mysql_flag){
                $model_order->db->query('rollback');
                return;
            }
            /* 交易成功后,推荐者可以获得佣金  END */

            /* 用户确认收货后 扣除商城佣金 */
            import('account.lib');
            $account = new account();
            $mysql_flag=$account->trade_charges($order_info);
            if(!$mysql_flag){
                $model_order->db->query('rollback');
                return;
            }
        }
            $model_order->db->query('commit');
        /* 用户确认收货后 获得积分 */
        import('integral.lib');
        $integral = new Integral();
        $integral->change_integral_buy($order_info['buyer_id'], $order_info['goods_amount']);

        //卖家确认收货 发送短信给卖家
        import('mobile_msg.lib');
        $mobile_msg = new Mobile_msg();
        $mobile_msg->send_msg_order($order_info, 'check');
    }
    function _auto_evaluate()
    {
        $now = gmtime();

        /* 默认30天未评价自动好评 */
        $interval = empty($this->_config['evaluate_interval']) ? 30 * 24 * 3600 : intval($this->_config['evaluate_interval']);
        $goods_evaluation = array(
            'evaluation'    => 3,
            'comment'       => '',
            'credit_value'  => 1
        );

        /* 获取满足条件的订单 */
        $model_order =& m('order');

        /* 指定时间后已确认收货的未评价的 */
        $orders = $model_order->find(array(
            'conditions'    => "finished_time + {$interval} < {$now} AND evaluation_status = 0 AND status = " . ORDER_FINISHED,
            'fields'        => 'order_id, seller_id',
        ));

        /* 没有满足条件的订单 */
        if (empty($orders))
        {
            return;
        }

        $order_ids = array_keys($orders);

        /* 获取待评价的商品列表 */
        $model_ordergoods =& m('ordergoods');
        $order_goods = $model_ordergoods->find(array(
            'conditions'    => 'order_id ' . db_create_in($order_ids),
            'fields'        => 'rec_id, goods_id',
        ));

        /* 自动好评 */
        $model_ordergoods->edit(array_keys($order_goods), $goods_evaluation);
        $model_order->edit($order_ids, array(
                'evaluation_status' => 1,
                'evaluation_time'   => gmtime()
        ));

        $model_store =& m('store');

        /* 因为店铺ID有可能重复，因此 */
        $sellers = array();
        foreach ($orders as $order_id => $order)
        {
            $sellers[$order['seller_id']] = $order['seller_id'];
        }
        foreach ($sellers as $seller_id)
        {
            $model_store->edit($seller_id, array(
                'credit_value'  =>  $model_store->recount_credit_value($seller_id),
                'praise_rate'   =>  $model_store->recount_praise_rate($seller_id)
            ));
        }

        /* 因为商品ID有可能重复，因此 */
        $comments = array();
        foreach ($order_goods as $rec_id => $og)
        {
            $comments[$og['goods_id']]++;
        }
        $edit_comments = array();
        foreach ($comments as $og_id => $t)
        {
            $edit_comments[$t][] = $og_id;
        }

        $model_goodsstatistics =& m('goodsstatistics');
        foreach ($edit_comments as $times => $goods_ids)
        {
            $model_goodsstatistics->edit($goods_ids, 'comments=comments+' . $times);
        }
    }

    function _close_expired_store()
    {
        $store_mod =& m('store');
        $stores = $store_mod->find(array(
            'conditions' => "state = '" . STORE_OPEN . "' AND end_time > 0 AND end_time < '" . gmtime() . "'",
            'join'       => 'belongs_to_user',
            'fields'     => 'store_id, user_id, user_name, email',
        ));

        /* 无过期店铺 */
        if (empty($stores))
        {
            return;
        }

        $ms =& ms();
        $store_ids = $store_emails = array();

        /* 消息内容 */
        $content = get_msg('toseller_store_expired_closed_notify');

        foreach ($stores as $store)
        {
            $store_ids[] = $store['store_id'];
            $store_emails[] = $store['email'];
        }

        
        $ms->pm->send(MSG_SYSTEM, $store_ids, '', $content);
        
        
        
        $store_mod->edit($store_ids, array('state' => STORE_CLOSED, 'close_reason' => Lang::get('toseller_store_expired_closed_notify')));
    }

    function _group_auto_start()
    {
        $groupbuy_mod =& m('groupbuy');
        $groupbuy_mod->edit(
            "state = '" . GROUP_PENDING . "' AND start_time > 0 AND start_time < '" . gmtime() . "'",
            array(
                'state' => GROUP_ON,
        ));
    }

    function _group_auto_end()
    {
        $ms =& ms();
        $groupbuy_mod =& m('groupbuy');
        $groups = $groupbuy_mod -> find(array(
            'conditions' => "gb.state = '" . GROUP_ON . "' AND gb.end_time > 0 AND gb.end_time < '" . gmtime() . "'",
            'join' => 'belong_store',
        ));
        $content = get_msg('toseller_groupbuy_end_notify',array('cancel_days' => GROUP_CANCEL_INTERVAL));
        foreach ($groups as $group)
        {
            $group_ids [] = $group['group_id'];
            $ms->pm->send(
                MSG_SYSTEM,
                $group['store_id'],
                '',
                $content
            );
        }
        if (!empty($group_ids))
        {
            $groupbuy_mod->edit($group_ids,array('state' => GROUP_END));
        }

    }

    function _group_auto_cancel()
    {
        /* 自动取消团购的天数 */
        $interval = GROUP_CANCEL_INTERVAL * 3600 * 24;

        $groupbuy_mod =& m('groupbuy');
        $groups = $groupbuy_mod -> findAll(array(
            'conditions' => "gb.state = '" . GROUP_END . "' AND gb.end_time > 0 AND gb.end_time + {$interval} < '" . gmtime() . "'",
            'join' => 'belong_store',
            'include' => array('be_join')
        ));

        // 短信通知
        $ms =& ms();
        $userpriv_mod = &m('userpriv');
        foreach ($groups as $group)
        {
            // 管理员
            $admin_id = $userpriv_mod->get_admin_id();
            $to_id = array_keys($admin_id);

            $group_ids[] =  $group['group_id'];

            // 参与团购的用户
            if (!empty($group['member']))
            {
                foreach ($group['member'] as $join_user)
                {
                    $to_id[] = $join_user['user_id'];
                }
                $to_id = array_unique($to_id);
            }
            
            $content = get_msg('tobuyer_group_auto_cancel_notify', array('cancel_days' => GROUP_CANCEL_INTERVAL, 'url' => SITE_URL . '/' . url("app=groupbuy&id=" . $group['group_id'])));
            $ms->pm->send(
                MSG_SYSTEM,
                $to_id,
                '',
                $content
            );

        }

        // 取消团购活动
        empty($group_ids) || $groupbuy_mod->edit($group_ids, array('state' => GROUP_CANCELED));
    }
}

?>
